package cn.iocoder.yudao.module.system.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.service.userretention.UserRetentionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * 用户留存率计算定时任务
 * 
 * 每日凌晨执行，计算前一天的用户留存率数据
 *
 * @author 系统
 */
@Component
@Slf4j
public class UserRetentionCalculationJob implements JobHandler {

    @Resource
    private UserRetentionService userRetentionService;

    @Override
    public String execute(String param) throws Exception {
        log.info("开始执行用户留存率计算定时任务");
        
        try {
            // 计算前一天的留存率
            LocalDate targetDate = LocalDate.now().minusDays(1);
            log.info("计算目标日期：{}", targetDate);
            
            // 执行留存率计算
            userRetentionService.calculateRetentionRate(targetDate);
            
            // 清理过期数据（保留90天）
            LocalDate expiredDate = LocalDate.now().minusDays(90);
            int deletedCount = userRetentionService.deleteExpiredData(expiredDate);
            
            String result = String.format("用户留存率计算完成，目标日期：%s，清理过期数据：%d条", 
                                         targetDate, deletedCount);
            log.info(result);
            
            return result;
        } catch (Exception e) {
            log.error("用户留存率计算定时任务执行失败", e);
            throw e;
        }
    }
}